package cn.groupmarket.domain.trade.service.impl;

import cn.groupmarket.domain.trade.adapter.repository.ITradeOrderRepository;
import cn.groupmarket.domain.trade.model.aggregate.GroupBuyOrderAggregate;
import cn.groupmarket.domain.trade.model.entity.*;
import cn.groupmarket.domain.trade.model.valobj.GroupBuyProgressVO;
import cn.groupmarket.domain.trade.service.ITradeOrderService;
import cn.groupmarket.domain.trade.service.factory.TradeRuleFilterFactory;
import cn.groupmarket.types.design.framework.link.model2.chain.BusinessLinkedList;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class TradeOrderService implements ITradeOrderService {
    @Resource
    private ITradeOrderRepository tradeOrderRepository;
    @Resource( name = "tradeRuleFilter")
    private BusinessLinkedList<TradeRuleCommandEntity, TradeRuleFilterFactory.DynamicContext, TradeRuleFilterBackEntity> tradeRuleFilter;


    @Override
    public MarketPayOrderEntity queryNoPayMarketPayOrderByOutTradeNo(String outTradeNo, String userId) {
        log.info("拼团交易，查询未支付订单:{} outTradeNo:{}", userId, outTradeNo);
        return tradeOrderRepository.queryNoPayMarketPayOrderByOutTradeNo(outTradeNo, userId);
    }

    @Override
    public GroupBuyProgressVO queryGroupBuyProgress(String teamId) {
        GroupBuyProgressVO groupBuyProgressVO = tradeOrderRepository.queryGroupBuyProgress(teamId);
        log.info("查询拼单进度:{}   {} {} {}", teamId,groupBuyProgressVO.getTargetCount(),groupBuyProgressVO.getCompleteCount(),groupBuyProgressVO.getLockCount());
        return groupBuyProgressVO;
    }

    @Override
    public MarketPayOrderEntity lockMarketPayOrder(UserEntity userEntity, PayDiscountEntity payDiscountEntity, PayActivityEntity payActivityEntity) throws Exception {
        log.info("拼团交易-锁定营销优惠支付订单:{} activityId:{} goodsId:{}", userEntity.getUserId(), payActivityEntity.getActivityId(), payDiscountEntity.getGoodsId());

        log.info("进入交易规则检测");

        TradeRuleFilterBackEntity tradeRuleFilterBackEntity = tradeRuleFilter.apply(TradeRuleCommandEntity.builder()
                        .activityId(payActivityEntity.getActivityId())
                        .userId(userEntity.getUserId())
                        .build(), new TradeRuleFilterFactory.DynamicContext());

        GroupBuyOrderAggregate groupBuyOrderAggregate = GroupBuyOrderAggregate.builder()
                .userEntity(userEntity)
                .payDiscountEntity(payDiscountEntity)
                .payActivityEntity(payActivityEntity)
                .userTakeOrderCount(tradeRuleFilterBackEntity.getUserTakeOrderCount())
                .build();

        return tradeOrderRepository.lockMarketPayOrder(groupBuyOrderAggregate);
    }
}
